<template>
  <div class="secondaryClassification">
    <div class="btnGrounp">
      <el-button @click="handleEdit(0)">新增二级分类</el-button>
    </div>
    <div class="search">
      <ul>
        <li>
          <span>所属一级分类</span>
          <el-select v-model="search.classLevel1" placeholder="请选择" @visible-change='getAllClassOne'>
            <el-option v-for="item in search.classLevel1Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </li>
        <li>
          <span>二级分类</span>
          <el-input v-model="search.classLevel2" placeholder="请输入内容" @keyup.enter.native="searchSecondary"></el-input>
        </li>
        <li class="lastLi">
          <el-button @click="searchSecondary">查询</el-button>
        </li>
      </ul>
    </div>
    <div class="content">
       <el-table :data="contentData" style="width: 100%" stripe :header-cell-class-name='lastTaHead'>
        <el-table-column prop="sort" label="排序" width="20%"  align='center'></el-table-column>
        <el-table-column label="图标" width="20%" align='center'>
          <template slot-scope="scope">
            <img :src="scope.row.icon" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="classOneName" label="一级分类" width="20%" align='center' ></el-table-column>
        <el-table-column prop="chinaName" label="二级分类" width="20%" align='center' show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align='center' width="100%" class-name='lastTd'>
          <template slot-scope="scope">
            <el-button class="edit" size='mini'  @click="handleEdit(1,scope.$index, scope.row)">编辑</el-button>
            <el-button  class="delete" size='mini' type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button class="adjust"  size='mini' @click="handleAdjust(scope.$index, scope.row)" v-if='scope.row.showAdjust'>调整排序</el-button>
            <div class="adjustSort" v-else>
              <el-input v-model="scope.row.adjustValue" placeholder="请输入内容"  @keyup.enter.native="sureAdjust(scope.row.id,scope.row)"></el-input> <el-button class="defaultBtn" @click="sureAdjust(scope.row.id,scope.row)">确定</el-button>
            </div>
          </template>
        </el-table-column >
      </el-table>
    </div>
    <!-- 弹框 -->
    <div class="dialog">
      <el-dialog :title="formTitle" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="图标" label-width="7.5rem">
            <!-- :data="upLoadData" -->
            <el-upload class="avatar-uploader" action="111"   :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="form.icon" :src="form.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="tips" v-if="isAdd">
              <span>W：275像素</span><br>
              <span>H：230像素</span>           
            </div>
          </el-form-item>
           <el-form-item label="所属一级分类" label-width="7.5rem">
             <el-select v-model="form.classOneId" placeholder="请选择" @visible-change='getAllClassOne'>
              <el-option v-for="item in form.class1Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类名-中文" label-width="7.5rem">
            <el-input v-model="form.chinaName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="分类名-英文" label-width="7.5rem">
            <el-input v-model="form.englishName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="secondaryClass">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="paging">
      <el-pagination :page-size="pageSize"  layout="prev, pager, next" :total="totalNum" @current-change='changeCurrentPage'></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'secondaryClassification',
  data () {
    return {
      search:{
        classLevel1:'',
        classLevel1Options: [],
        classLevel2:'',//二级分类
      },//查询对象
      //内容数据
      contentData: [],
      pageSize:7,//每页显示条目个数
      totalNum:7,//总条目数   
      currentPage:1,
      formTitle: '编辑',//表单标题
      dialogFormVisible:false,//对话框是否可见
      //对话框表单
      form: {
          icon: '',
          iconKey: '',
          classOneId:'',//序列号状态
          class1Options: [],
          chinaName: '',
          englishName: '',
        },
      id:"",//操作某一行的id
      isAdd:true,//新增显示图片tips
      // upLoadData:{//上传时附带的其他参数
      //     srid:''
      // }
    }
  },
  methods: {
    //编辑行
    handleEdit(type,index, row) {
      let _this = this;
      // console.log(type,index, row);
      _this.dialogFormVisible = true;//显示对话框

      if(type == 0){//新增操作
        _this.formTitle = '新增';
        _this.form.chinaName = '';
        _this.form.englishName = '';
        _this.form.icon = '';
        _this.form.iconKey = '';
        _this.form.classOneId = '';

        _this.isAdd = true;//新增显示图片tips
      }else{//编辑操作
        _this.formTitle = '编辑';
        _this.id = row.id;
        _this.isAdd = true;//编辑不显示图片tips
        let sessionId = _this.$store.state.id;//获取token
        let api = '/api/sysClassTwo/find_detail?id='+_this.id;
        _this.axios({
          url:api,
          method: 'post',
          headers:{
            sessionId,
          }		
        }).then(res=>{
          //console.log('编辑行',res);
          if(res.data.code == 401){
          _this.$message({
            type: 'info',
            message: '登录已失效，请重新登录'
          });  
          _this.$router.push({
            path:"/"
          });
          return
        }
          _this.form.chinaName = res.data.data.bussData.chinaName;
          _this.form.englishName = res.data.data.bussData.englishName;
          _this.form.icon = res.data.data.bussData.icon;
          _this.form.iconKey = '';
          _this.form.classOneId = res.data.data.bussData.classOneId;
        });
        //console.log('id',_this.id);
      }

    },
    //操作第二分类
    secondaryClass(){
      let _this = this;
      if(_this.form.icon == ''){
        _this.$message('请先上传图片');
        return
      }
      if(_this.form.chinaName == '' || _this.form.englishName == '' || _this.form.classOneId == ''){
        _this.$message('请先输入中文名或英文名或请先选择序列号状态');
        return
      }
      let reg = /^[a-zA-Z]+$/;
      if(!reg.test(_this.form.englishName.replace(/\s+/g,""))){
        _this.$message('请确认输入英文名字');
        return
      }
      let api = '';
      let data = '';//传参
      let sessionId = _this.$store.state.id;//获取token
      if(_this.formTitle == '新增'){
        api = '/api/sysClassTwo/insert';
        data = {
          "chinaName": _this.form.chinaName,
          "classOneId": _this.form.classOneId,
          "englishName": _this.form.englishName,
          "icon": _this.form.iconKey,
        };
        
      }else{//编辑
        api = '/api/sysClassTwo/update';
        data = {
          "chinaName": _this.form.chinaName,
          "classOneId": _this.form.classOneId,
          "englishName": _this.form.englishName,
          "icon": _this.form.iconKey,
          'id':_this.id,
        };
      }
      _this.axios.post(api,data,{
        headers:{
          sessionId
        }
      }).then(res=>{
        //console.log('操作二级分类',res);
        if(res.data.code == 401){
          _this.$message({
            type: 'info',
            message: '登录已失效，请重新登录'
          });  
          _this.$router.push({
            path:"/"
          });
          return
        }
        if(res.data.code == 200){
          _this.$message({
            type: 'success',
            message: _this.formTitle+'成功！'
          }); 
          _this.form.chinaName = '';//清空字段
          _this.form.englishName = '';//清空字段
          _this.form.icon = '';//清空字段
          _this.form.classOneId = '';//清空字段
          _this.dialogFormVisible = false;//隐藏弹框
          _this.getAllSecondary();//刷新
        }
      });
    },
    //删除行
    handleDelete(index, row) {
      let _this = this;
      let sessionId = _this.$store.state.id;
      //console.log(index, row);
      _this.$confirm('是否删除?',  {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let api = '/api/sysClassTwo/delete?id='+row.id;
          _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
            //console.log('删除行',res)
            if(res.data.code == 401){
                _this.$message({
                  type: 'info',
                  message: '登录已失效，请重新登录'
                });  
                _this.$router.push({
                  path:"/"
                });
                return
            }
            if(res.data.code == 500){
              _this.$message(res.data.data.errMsg);
              return
            }
            if(res.data.code == 200){
              _this.$message({
                type: 'success',
                message: '删除成功!'
              });
              _this.getAllSecondary();//刷新
            }
          });
        }).catch(() => {
          _this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //调整排序
    handleAdjust(index, row) {
      let _this = this;
      //注意showAdjust是数组每一个对象元素添加属性，层次[{}]太深,且不是vue实例化时指定，所以出现了数据更改，
      //页面没有热响应的情况，需要用$set方法修改媒体{}的showAdjust属性，且用数组的splice热响应监听方法对
      //数组进行修改
      // _this.$set(row, 'showAdjust', false)
      // _this.contentData.splice(index, 1, row);
      // debugger
      _this.contentData.forEach((item,indexs)=>{
        //console.log(indexs, item);
        if(indexs == index){
          _this.$set(item, 'showAdjust', false)
          
        }else{
           _this.$set(item, 'showAdjust', true)
        }
        _this.contentData.splice(indexs, 1, item);

      });
      // _this.$forceUpdate();//强制刷新
      //console.log(index, row,_this.contentData);


    },
    //确定调整
    sureAdjust(id,row){
      let _this = this;
      let api = '/api/sysClassTwo/changeSort?id='+id+'&sort='+row.adjustValue;
      let sessionId = _this.$store.state.id;

      _this.axios({
          url:api,
          method: 'post',
          headers:{
            sessionId,
          }		
  			}).then(res=>{
        //console.log('确认修改顺序',res);
        if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          if(res.data.code == 200){
            _this.$message({
              type: 'success',
              message: '修改成功！'
            }); 
            _this.getAllSecondary();//刷新
          }
      });
    },
    //改变当前页
    changeCurrentPage(val){
      //console.log(`当前页: ${val}`);
      let _this = this;
      _this.currentPage = val;
      _this.getAllSecondary();//调用同一接口
    },
    //最后一列的表头
    lastTaHead({row, column, rowIndex, columnIndex}){
      let _this = this;
      if(columnIndex == 4){
        return 'lastTd lastTdHead'
      }
    },
    //图片上传成功实现本地预览
    handleAvatarSuccess(res, file) {
      let _this = this;
      _this.form.icon = URL.createObjectURL(file.raw);
    },
    //上传之前的钩子函数
    beforeAvatarUpload(file) {
      //console.log('上传文件',file);
      let _this = this;
      
      let sessionId = _this.$store.state.id;//获取token

      let suffix = file.name.split('.')[1];
      //console.log(suffix,'suffix');
      let contentType = file.type;
      //console.log('contentType',contentType);
      if(contentType.indexOf('image')<0){
          _this.$message('请上传图片');
          return
        }
      let api = '/api/base/app/getOSSUploadFormData/'+suffix;
      _this.axios.get(api,{
            // params:fd,
            headers:{
              sessionId,
            }
        })
      .then(function (res) {      
          //console.log('上传文件',res);
          if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          let key = res.data.data.bussData.fileKey;
          // _this.form.iconKey = res.data.data.bussData.fileKey;
          // _this.form.icon  = res.data.data.bussData.downloadUrl;
          let uploadUrl = res.data.data.bussData.uploadUrl;
          let downloadUrl = res.data.data.bussData.downloadUrl;
          let uploadFormData = res.data.data.bussData.formData;
          // // let api2 = res.data.data.bussData.downloadUrl+'?fileKey='+_this.form.iconKey;
          // // // let api2 =  _this.form.icon  = res.data.data.bussData.downloadUrl;
          // // //console.log('api2',api2);
          let fd = new FormData();
          fd.append('OSSAccessKeyId',uploadFormData.OSSAccessKeyId);//传文件
          fd.append('signature',uploadFormData.signature);//传文件
          fd.append('success_action_status',uploadFormData.success_action_status);//传文件
          fd.append('key',uploadFormData.key);//传文件
          fd.append('policy',uploadFormData.policy);//传文件
          fd.append('file',file);//传文件
          _this.axios.post(uploadUrl,fd).then(res=>{
            //console.log('第二步上传res',res);
            if(res.status == 200){
              //console.log('第二步上传成功');
              _this.form.icon  = downloadUrl;
              _this.form.iconKey = key;
            }else{
              _this.$message({
                type: 'info',
                message: '上传失败，请重新上传'
              });  
            }
          }).catch(err=>{
            //console.log('第二步上传错误',err);
            _this.form.icon  = downloadUrl;
            _this.form.iconKey = key;
            
          });
      })
      .catch(function (error) {
        //console.log('上传错误',error);
      })
      return false//屏蔽了action的默认上传
    },
    //获取所有二级分类列表
    getAllSecondary(searchPage){
      let _this = this;
      let api = '/api/sysClassTwo/find_page';
      let sessionId = _this.$store.state.id;//获取token
      //console.log(_this.search.classLevel1,'所属一级分类');
      _this.axios.post(api,{
        "chinaNameLike": _this.search.classLevel2,
        "classOneId": _this.search.classLevel1,
        "pageIndex": searchPage == 1?searchPage:_this.currentPage,
        "pageSize": 7,
      },{
        headers:{
          sessionId,
        }
      }).then(res=>{
        //console.log('所有二级分类',res)
        if(res.data.code == 401){
          _this.$message({
            type: 'info',
            message: '登录已失效，请重新登录'
          });  
          _this.$router.push({
            path:"/"
          });
          return
        }
        if(res.data.code == 403){
          _this.$message({
            type: 'info',
            message: res.data.status
          });  
          return
        }
        if(res.data.code == 200){
          _this.totalNum = res.data.data.count;//获取总条数
          _this.contentData = res.data.data.bussData;
          _this.contentData.forEach(item=>{
            item.showAdjust = true;
          });
        }
      });
    },
    //查询二级分类
    searchSecondary(){
      let _this = this;
      _this.getAllSecondary(1);//调用同一接口
    },
    // //获取所有一级分类
    getAllClassOne(isShow){
      let _this = this;
      //console.log(isShow,'下拉框是否出现');
      if(!isShow){
        return
      }
      let api = '/api/sysClassOne/find_list';
      let optionsOne = [];//清空  
      let sessionId = _this.$store.state.id;//获取token   
      _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
        //console.log('查询所有的一级分类',res)
             
        let class1 = res.data.data.bussData;
        class1.forEach(item=>{
          let obj = {};
          obj.value = item.id;
          obj.label = item.chinaName;
          optionsOne.push(obj);
          // _this.form.class1Options.push(obj);
        });
        // //console.log('optionsOne',optionsOne);
        optionsOne = optionsOne.filter(item=>{
          return item.label !='全部'
        });
        //console.log('optionsOne',optionsOne);
        _this.$store.dispatch('saveClassOne',optionsOne);//缓存所有一级分类
        _this.search.classLevel1Options = _this.$store.state.classOneOptions.slice(0);//获取所有第一分类
        _this.form.class1Options = _this.$store.state.classOneOptions.slice(0);//获取所有第一分类
        let obj = {
          value:"",
          label:"全部",
        }
        _this.search.classLevel1Options.unshift(obj);
        _this.form.class1Options.unshift(obj);
        _this.search.classLevel1 = _this.form.classOneId = '';
        // //console.log('saveClassOne',optionsOne,_this.$store.state.classOneOptions);


      });
    }

  },
  mounted(){
    let _this = this;
    _this.getAllSecondary();//获取所有二级分类
    _this.getAllClassOne(true);//获取所有一级分类
    // if(_this.$store.state.classOneOptions.length == 0){
    //   _this.getAllClassOne();//获取所有一级分类

    // }else{
    //   _this.search.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
    //   _this.form.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
    // }
    // let optionsOne = _this.$store.state.classOneOptions;
    // optionsOne = optionsOne.filter(item=>{
    //   return item.label !='全部'
    // });
    // //console.log('_this.$store.state.classOneOptions',_this.$store.state.classOneOptions);
    // _this.search.classLevel1Options = optionsOne.slice(0);//获取所有第一分类
    // _this.form.class1Options = optionsOne.slice(0);//获取所有第一分类
    // //console.log(_this.form.class1Options,'_this.form.class1Options');
    // //console.log(_this.form.class1Options,_this.search.classLevel1Options,'_this.search.classLevel1Options');
    
    let obj = {
      value:"",
      label:"全部",
    }

    _this.search.classLevel1Options.unshift(obj);
    _this.form.class1Options.unshift(obj);
    //console.log(_this.form.class1Options,_this.search.classLevel1Options,'_this.search.classLevel1Options');
    _this.search.classLevel1 = _this.form.classOneId = '';
  }
}
</script>

<style scoped>
/* 整体样式 */
.secondaryClassification{
  height: 100%;
  width: 100%;
  position: relative;
  padding-left: 2%;
}
.secondaryClassification>>>.btnGrounp .el-button{
  background-color: rgba(53, 174, 160, 1);
  color: rgb(255, 255, 255,1);
}
/* 查询 */
.secondaryClassification>>>.search{
  width: 100%;
  height: 10%;
  line-height: 10%;
  position: absolute;
  top: 10%;
  font-size: .875rem;
}
/* 输入框 */
.secondaryClassification>>>.el-input{
  width: 70%;
}
/* 输入框 */
.secondaryClassification>>>.el-select{
  width: 50%;
}
/* 选择框下的输入框 */
.secondaryClassification>>>.el-select .el-input{
  width: 140%;
}
.secondaryClassification>>>.search ul{
  width: 100%;
  height: 100%;
  display: flex;
  
}
.secondaryClassification>>>.search ul li{
  /* flex:1; */
  padding-right: 2%;
}
.secondaryClassification>>>.search ul li.lastLi{
    position:absolute;
    right: 15%;
}
.secondaryClassification>>>.search ul li span{
  padding-right: 2%;
}
.secondaryClassification>>>.search ul li.lastLi button{
  color:rgba(16, 16, 16, 1);
}
/* 主要内容 */
.secondaryClassification>>>.content{
  width: 85%;
  position: absolute;
  top: 21%;
  color: rgba(16, 16, 16, 1) !important;
}
.secondaryClassification>>>.content img{
  width: 21%;
}
.secondaryClassification>>>.content table{
  width: 100% !important;
}
/* table无数据时的显示 */
.secondaryClassification>>>.el-table__empty-block{
   width: 100% !important;
}
/* 最后一列 */
.secondaryClassification>>>.lastTd{
  text-align: left;
  padding-left: 2%;
}
/* 消除表头变形 */
.secondaryClassification>>>table .gutter{
  display: block !important;
}
.secondaryClassification>>>.lastTd .cell{
   height: 1.75rem;
  line-height: 1.75rem;

}
.secondaryClassification>>>.content table td .cell{
  width: 100% !important;
}
/* .secondaryClassification>>>.lastTd .cell{
  height: 20%;
  line-height: 20%;
} */
/* 最后一列表头 */
.secondaryClassification>>>.lastTdHead{
  padding-left: 10%;
}
/* 表格内的按钮 */
.secondaryClassification>>>.content table .defaultBtn{
  color: rgba(16, 16, 16, 1);
}
/* 编辑按钮 */
.secondaryClassification>>>.edit{
  background-color: rgba(63, 81, 181, 1);
}
/* 删除按钮 */
.secondaryClassification>>>.delete{
  background-color: rgba(229, 28, 35, 1);
}
/* 调整排序按钮 */
.secondaryClassification>>>.adjust{
  background-color: rgba(139, 195, 74, 1);

}
/* 调整排序输入框 */
.secondaryClassification>>>.adjustSort{
  display: inline-block;
  height: 92%;
}
.secondaryClassification>>>.adjustSort .el-input{
  width: 42%;
  height: 100%;

}
.secondaryClassification>>>.adjustSort .el-input input{
  height: 100%;
}
.secondaryClassification>>>.adjustSort .el-input__inner{
  /* height: 1.9375rem; */
}
.secondaryClassification>>>.adjustSort .el-button{
  line-height: 0.07;
  /* height: 100%;
  line-height: 1.75rem; */

}
/* 分页 */
.secondaryClassification>>>.paging{
  position: absolute;
  bottom: 0%;
  text-align: center;
  width: 85%;
}
/* 对话框 */
.secondaryClassification>>>.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .secondaryClassification>>>.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .secondaryClassification>>>.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .secondaryClassification>>>.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  /* 弹框图片tips */
  .secondaryClassification>>>.tips{
    position: absolute;
    top: 20%;
    left: 37%;
  }
</style>
